package leetcode

type DetectSquares struct {
	row    map[int][]int
	column map[int][]int
	xys    map[xy]int
}

type xy struct {
	x, y int
}

func Constructor1() DetectSquares {
	return DetectSquares{
		row:    make(map[int][]int),
		column: make(map[int][]int),
		xys: make(map[xy]int),
	}
}

func (this *DetectSquares) Add(point []int) {
	i, j := point[0], point[1]
	if _, ok := this.row[i]; !ok {
		this.row[i] = make([]int, 0)
	}
	if _, ok := this.column[j]; !ok {
		this.column[j] = make([]int, 0)
	}
	this.row[i] = append(this.row[i], j)
	this.column[j] = append(this.column[j], i)
	this.xys[xy{
		x: i,
		y: j,
	}] ++
}

func (this *DetectSquares) Count(point []int) int {
	i, j := point[0], point[1]
	res := 0
	row := this.row[i]
	column := this.column[j]
	for x := range row {
		for y := range column {
			ix,iy:=column[y],row[x]
			if this.xys[xy{ix,iy}]>0&& isRactangles(i,j,ix,iy){
				res+=this.xys[xy{ix,iy}]
			}
		}
	}
	return res
}

func isRactangles(x1,y1,x2,y2 int) bool {
	diff1,diff2:=x1-x2,y1-y2
	if diff1<0{
		diff1*=-1
	}
	if diff2<0{
		diff1*=-1
	}
	if diff1==diff2{
		return true
	}
	return false
}